# -*- encoding: utf-8 -*-

"""
@File:      tc_readline_fun_002.py
@Time:      2024-02-28 11:30:00
@Author:    qintingting
@Version:   1.0
@Contact:   wb-qtt862918@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    qintingting
"""
import pexpect
from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_readline_fun_002.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "readline readline-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline='''cat > readline_fun_002.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <readline/readline.h>
#include <readline/history.h>

char *commands[] = {
    "help",
    "quit",
    "add",
    "subtract",
    NULL
};

char* command_generator(const char* text, int state) {
    static int list_index, len;
    char *name;

    if (!state) {
        list_index = 0;
        len = strlen(text);
    }

    while ((name = commands[list_index]) != NULL) {
        list_index++;

        if (strncmp(name, text, len) == 0) {
            return strdup(name);
        }
    }

    return NULL;
}

char** command_completion(const char* text, int start, int end) {
    rl_attempted_completion_over = 1;
    return rl_completion_matches(text, command_generator);
}

int main() {
    rl_attempted_completion_function = command_completion;

    char *input;
    while (1) {
        input = readline(">> ");

        if (strcmp(input, "exit") == 0) {
            break;
        }

        add_history(input);
        printf("%s\\n", input);
        free(input);
    }

    free(input);
    return 0;
}
EOF
'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o readline_fun_002 readline_fun_002.c -lreadline")
        code, result = self.cmd("file readline_fun_002")
        self.assertIn("executable", result)
        child = pexpect.spawnu('./readline_fun_002')
        child.expect(r'>> ') 
      
        # use Ctrl+i to simulate the Tab key for automatic completion 
        commands_dict = {'h': 'help', 'q': 'quit', 'a': 'add', 's': 'subtract'}
        for prefix, completion in commands_dict.items():
            child.send(prefix)
            child.sendcontrol('i')
            child.sendline()
            # check if the completion is correct
            try:
                child.expect(completion)
                print(f"'{completion}' Command auto-completion successful.")
            except pexpect.exceptions.EOF:
                print(f"'{completion}' Command auto-completion failed or program terminated unexpectedly.")
                exit(1)
       

        child.sendline('exit')
        child.expect(pexpect.EOF)
        child.close()
     
        # confirm exit status
        if child.exitstatus == 0:
            print('Program exited successfully.')
        else:
            print('Program did not exit successfully.')
            
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf readline_fun_002 readline_fun_002.c")